<?php

SDV($HandleActions['mindmap'],'HandleMindmap');
SDV($HandleActions['mindmapfull'],'HandleMindmapFull');
SDV($HandleActions['mmconv'],'HandleMindmapConvert');
SDV($mmMarkerArticle, 'Category.MindMap');

$oldHandleBrowseFunc = $HandleActions['browse'];
$HandleActions['browse'] = 'mmHandleBrowse';

$HTMLStylesFmt['mindmap'] = <<<MINDMAP_CSS
	/* hide from ie on mac */
	#flashcontent {
		width: 100%;
		height: 500px;
	}
	/* end hide */
MINDMAP_CSS;

$HTMLHeaderFmt['mindmap'] = <<<MINDMAP_HEADER
	<script type="text/javascript" src="$PubDirUrl/vietmap/flashobject.js"></script>
	<script language="javascript">
		function giveFocus() 
		{ 
		  document.visorFreeMind.focus();  
		}
	</script>
MINDMAP_HEADER;

function HandleMindmap($pagename) {
  global $PageStartFmt,$PageMindmapFmt,$PageEndFmt,$PubDirUrl,$ScriptUrl;
  SDV($PageMindmapFmt, <<<MINDMAP_FMT
        <div id="flashcontent" onmouseover="giveFocus();">Flash plugin or Javascript are turned off. 		 Activate both  and reload to view the mindmap</div>
        <script type="text/javascript">
		// <![CDATA[
		// for allowing using http://.....?mindmap.mm mode
		function getMap(map){
		  var result=map;
		  var loc=document.location+'';
		  if(loc.indexOf(".mm")>0 && loc.indexOf("?")>0){
			result=loc.substring(loc.indexOf("?")+1);
		  }
		  return result;
		}
		var fo = new FlashObject("$PubDirUrl/vietmap/visorFreemind.swf", "visorFreeMind", "100%", "100%", 6, "#9999ff");
		fo.addParam("quality", "high");
		fo.addParam("bgcolor", "#a0a0f0");
		fo.addVariable("openUrl", "_blank");
		fo.addVariable("startCollapsedToLevel","-1");
		fo.addVariable("maxNodeWidth","200");
		fo.addVariable("mainNodeShape","elipse");
		fo.addVariable("justMap","false");
		fo.addVariable("initLoadFile","$ScriptUrl?n=$pagename&action=mmconv");
		fo.addVariable("defaultToolTipWordWrap",200);
		fo.addVariable("offsetX","left");
		fo.addVariable("offsetY","top");
		fo.addVariable("buttonsPos","top");
		fo.addVariable("min_alpha_buttons",20);
		fo.addVariable("max_alpha_buttons",100);
		fo.addVariable("scaleTooltips","false");
		fo.write("flashcontent");
		// ]]>
	</script>
MINDMAP_FMT
);
  PrintFmt($pagename, array(&$PageStartFmt,&$PageMindmapFmt,&$PageEndFmt));
}

function HandleMindmapFull($pagename) {
  global $PubDirUrl,$ScriptUrl;
	echo <<<MINDMAP_FULL_FMT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xml:lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="description" content="freemind flash browser" />
        <meta name="keywords" content="r7group, java, learn" />
        <meta name="expires" content="0" />
		<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
		<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
        <title>Simple MindMap - $pagename</title>
        <script type="text/javascript" src="$PubDirUrl/vietmap/flashobject.js"></script> <style type="text/css">
	
	/* hide from ie on mac */
	html {
		height: 100%;
		overflow: hidden;
	}

	#flashcontent {
		height: 100%;
	}
	/* end hide */

	body {
		height: 100%;
		margin: 0;
		padding: 0;
		background-color: #9999ff;
	}

</style> <script language="javascript">
function giveFocus() 
    { 
      document.visorFreeMind.focus();  
    }
</script>
    </head>
    <body spellcheck="false">
        <div id="flashcontent" onmouseover="giveFocus();">Flash plugin or Javascript are turned off. 		 Activate both  and reload to view the mindmap</div>
        <script type="text/javascript">
		// <![CDATA[
		// for allowing using http://.....?mindmap.mm mode
		function getMap(map){
		  var result=map;
		  var loc=document.location+'';
		  if(loc.indexOf(".mm")>0 && loc.indexOf("?")>0){
			result=loc.substring(loc.indexOf("?")+1);
		  }
		  return result;
		}
		var fo = new FlashObject("$PubDirUrl/vietmap/visorFreemind.swf", "visorFreeMind", "100%", "100%", 6, "#9999ff");
		fo.addParam("quality", "high");
		fo.addParam("bgcolor", "#a0a0f0");
		fo.addVariable("openUrl", "_blank");
		fo.addVariable("startCollapsedToLevel","-1");
		fo.addVariable("maxNodeWidth","200");
		//
		fo.addVariable("mainNodeShape","elipse");
		fo.addVariable("justMap","false");
		fo.addVariable("initLoadFile","$ScriptUrl?n=$pagename&action=mmconv");
		fo.addVariable("defaultToolTipWordWrap",200);
		fo.addVariable("offsetX","left");
		fo.addVariable("offsetY","top");
		fo.addVariable("buttonsPos","top");
		fo.addVariable("min_alpha_buttons",20);
		fo.addVariable("max_alpha_buttons",100);
		fo.addVariable("scaleTooltips","false");
		fo.write("flashcontent");
		// ]]>
	</script>
    </body>
</html>
MINDMAP_FULL_FMT;
}

function mm_compare($a, $b) {
	if ($a === '') {
		return 1;
	}
	if ($a === false) {
		return -1;
	}
	if (substr($a, 0, 1) == '!' && substr($b, 0, 1) != '!') {
		return 1;
	}
	if (substr($a, 0, 1) != '!' && substr($b, 0, 1) == '!') {
		return -1;
	}
	$m = (substr($a, 0, 1) == '-') ? strlen($a)-1 : strlen($a);
	$n = (substr($b, 0, 1) == '-') ? strlen($b)-1 : strlen($b);
	return $n - $m;
}

function HandleMindmapConvert($pagename) {
	$levelRegex = '/^(-+>|#+|\*+|!+)(?:\s*)/';
	$page = ReadPage($pagename);
	$title = ($page['title'] == '' ? $pagename : $page['title']);
	$lines = preg_split('/\r?\n/', $page['text']);
	$levels = array('');
	$n = 0;
	$id = 123;
	
	// count highest nodes
	$highestcount = 0;
	$highest = false;
	foreach ($lines as $line) {
		if (preg_match($levelRegex, $line, $matches0) > 0) {
			$cmp = mm_compare($highest, $matches0[1]);
			if ($cmp < 0) {
				$highest = $matches0[1];
				$highestcount = 1;
			} else if ($cmp == 0) {
				$highestcount++;
			}
		}
	}
	//die("$highestcount: $highest");
	
	// convert
	$result = "<map>\n";
	$result .= '<node TEXT="' . $title . '">' . "\n";
	$position = 1;
	$k = 0; // highest level occurences so far
	foreach ($lines as $line) {
		if (preg_match($levelRegex, $line, $matches) > 0) {
			$content = substr($line, strlen($matches[0]));
			while (($cmp = mm_compare($levels[$n], $matches[1])) < 0) {
				$result .= str_repeat('  ', $n) . "</node>\n";
				$n--;
			}
			if ($cmp > 0) {
				$levels[++$n] = $matches[1];
			} else {
				$result .= str_repeat('  ', $n) . "</node>\n";
			}
			// convert to html and strip <p>, <a> tag (if any)
			$html = MarkupToHTML($pagename, $content);
			$href = null;
			$name = null;
			if (preg_match('/^\s*<p>(.*)\r?\n<\/p>\s*$/s', $html, $matches2)) {
				$html = $matches2[1];
			}
			if (preg_match('/^\s*<a.*href=["\']([^"\']+)["\'].*>(.*)<\/a>\s*$/s', $html, $matches3)) {
				$href = $matches3[1];
				$html = $matches3[2];
			}
			if (preg_match('/^\s*<a.*name=["\']([^"\']+)["\'].*>(.*)<\/a>/', $html, $matches5)) {
				$name = $matches5[1];
				$html = $matches5[2] . substr($html, strlen($matches5[0]));
			}
			// allow only src property in <img>
			// support 01 <img> only because flash browser can't display 2 or more properly
			if (preg_match('/<img.*src=["\']([^"\']+)["\'].*\/>/s', 
					$html, $matches4, PREG_OFFSET_CAPTURE)) {
				$html = substr_replace($html, "<img src='{$matches4[1][0]}' />", 
						$matches4[0][1], strlen($matches4[0][0]));
			}
			// append to result
			$result .= str_repeat('  ', $n) . '<node TEXT="' . htmlspecialchars("<html>$html") . '"';
			if ($href != null) {
				$result .= ' LINK="' . $href . '"';
			}
			if ($name != null) {
				$result .= ' ID="' . $name . '"';
			}
			if ($n == 1) {
				$result .= ' POSITION="' . ($k++ >= $highestcount/2  ? 'left' : 'right') . '"';
			}
			$result .= ">\n";
		}
	}
	while ($n > 0) {
		$result .= str_repeat('  ', $n) . "</node>\n";
		$n--;
	}
	$result .= "</node>\n</map>";
	// output
	header('Content-Type: text/xml');
	echo($result);
}

function mmHandleBrowse($pagename) {
	global $oldHandleBrowseFunc, $mmMarkerArticle;
	if (!isset($_GET['action']) && !isset($_POST['action'])) {
		$page = ReadPage($pagename);
		if (preg_match("/(?:^|,)$mmMarkerArticle(?:,|$)/", $page['targets'])) {
			HandleMindmap($pagename);
			return;
		}
	}
	$oldHandleBrowseFunc($pagename);
}
